package com.xingchi.tornado.core.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

/**
 * excel读取监听器
 *
 * @author xingchi
 * @date 2024/11/24 20:18
 */
public class ExcelReadListener<T> extends AnalysisEventListener<T> {

    /**
     * 存储数据
     */
    private final List<T> dataList;

    /**
     * 回调函数
     */
    private final Consumer<List<T>> callback;

    /**
     * 是否批量处理
     */
    private final boolean isBatch;

    /**
     * 批量处理大小
     */
    private final int batchSize;

    /**
     * 默认批量处理大小
     */
    public static final int DEFAULT_BATCH_SIZE = 500;

    public ExcelReadListener(Consumer<List<T>> callback) {
        this(callback, false);
    }

    public ExcelReadListener(Consumer<List<T>> callback, boolean isBatch) {
        this(callback, isBatch, DEFAULT_BATCH_SIZE);
    }

    public ExcelReadListener(Consumer<List<T>> callback, boolean isBatch, int batchSize) {
        this.callback = callback;
        this.isBatch = isBatch;
        this.batchSize = batchSize;
        dataList = new ArrayList<>();
    }

    @Override
    public void invoke(T data, AnalysisContext analysisContext) {
        dataList.add(data);
        if (isBatch && dataList.size() >= batchSize) {
            // 执行回调函数
            callback.accept(dataList);
            dataList.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 所有的数据执行回调
        callback.accept(dataList);
    }
}
